package com.xc.ksxt.controller;

import com.alibaba.fastjson.JSONObject;
import com.xc.common.object.LayuiTableResponse;
import com.xc.common.object.PageInfo;
import com.xc.common.object.ResponseEntity;
import com.xc.common.tool.Helper;
import com.xc.db.tables.Lib;
import com.xc.db.tables.LibQuestion;
import com.xc.db.tables.Paper;
import com.xc.ksxt.entity.LibEntity;
import com.xc.ksxt.entity.QuestionEntity;
import com.xc.ksxt.service.LibService;
import com.xc.ksxt.vo.LibVO;
import com.xc.sys.service.SysUserService;
import com.xc.sys.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import static org.jooq.impl.DSL.*;
@RestController
@RequestMapping("/lib")
@CrossOrigin
public class LibController {
    @Autowired
    private DSLContext dsl;
    @Autowired
    private LibService libService;
    private LibQuestion LIBQUESTIONTB = LibQuestion.LIB_QUESTION.as("LIBQUESTIONTB");
    private Lib LIBTB = Lib.LIB.as("LIBTB");
    private Paper PAPERTB = Paper.PAPER.as("PAPERTB");
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
    @RequestMapping({"/getPageList"})
    public LayuiTableResponse<LibVO> getPageList(HttpServletRequest request) {
        LayuiTableResponse<LibVO> ltr = new LayuiTableResponse<>();
        Condition cond = LIBTB.STATE.notEqual(-1);
        String name = request.getParameter("name");
        String keywords = request.getParameter("keywords");
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        Integer page = Integer.valueOf(request.getParameter("page"));
        if (StringUtils.isNotBlank(name)) {
        	cond = cond.and(LIBTB.NAME.like("%"+name+"%"));
        }
        if (StringUtils.isNotBlank(keywords)) {
        	cond = cond.and(LIBTB.NAME.like("%"+keywords+"%"));
        }
        Long count = libService.count(cond);
        ltr.setCount(count);
        PageInfo<LibEntity> pageInfo = new PageInfo<>(limit, page);
        Result<Record> list = libService.select(cond, pageInfo,LIBTB.NAME.asc(),LIBTB.CREATE_TIME.desc());
        List<LibVO> libEntityList = list.into(LibVO.class);
        for (LibVO libEntity : libEntityList){
            setTxt(libEntity);
        }
        ltr.setData(libEntityList);
        return ltr;
    }

    private void setTxt(LibVO libEntity) {
        SysUserVO user = SysUserService.getFrameCaches(libEntity.getCreateUserId());
        libEntity.setCreateUserName(user==null?"":user.getName());
        if(libEntity.getCategoryId()!=null){
            String cname = dsl.select(field("name")).from(table("lib_category")).where(field("id").eq(Long.valueOf(libEntity.getCategoryId()))).fetchOneInto(String.class);
            libEntity.setCategoryName(cname);
        }
    }

    @RequestMapping({"/getById"})
    public LibVO getById(Integer id) {
        Record r = libService.getRecordById(id);
        LibVO entity = r.into(LibVO.class);
        setTxt(entity);
        return entity;
    }
    @RequestMapping({"/emptyLastUseDate"})
    public ResponseEntity<QuestionEntity> emptyLastUseDate() {
     //   Integer id = Integer.valueOf(params.get("id"));
        ResponseEntity<QuestionEntity> res = new ResponseEntity<>();
        dsl.fetch("update lib_question set last_use_date=null");
        return res;
    }
    @RequestMapping({"/save"})
    public ResponseEntity<LibEntity> save(@RequestBody HashMap<String,String> params, HttpServletRequest request) {
    	ResponseEntity<LibEntity> res = new ResponseEntity<>();
    	LibEntity libEntity = Helper.map2Bean(new LibEntity(), params);
    	libService.save(libEntity);
        return res;
    }
    @RequestMapping({"/delete"})
    public LayuiTableResponse<LibEntity> delete(@RequestParam("ids[]") Integer[] ids) {
        LayuiTableResponse<LibEntity> ltr = new LayuiTableResponse<>();
        for (Integer id : ids) {
        	LibEntity m = libService.getEntityById(id);
        	m.setDelFlag(-1);
        	libService.update(m);
        }
        return ltr;
    }
    @GetMapping("/getConsoleData")
    public JSONObject getConsoleData(){
        LocalDate firstDayOfYear = LocalDate.now().withDayOfYear(1);
        LocalDate lastDayOfYear = LocalDate.now().withDayOfYear(LocalDate.now().lengthOfYear());
        lastDayOfYear = lastDayOfYear.withDayOfMonth(lastDayOfYear.lengthOfMonth());
        JSONObject res = new JSONObject();
        Integer majorNum = dsl.selectCount().from(table("major")).fetchOneInto(Integer.class);
        Integer libNum = dsl.selectCount().from(table("lib")).fetchOneInto(Integer.class);
        Integer questionNum = dsl.selectCount().from(table("lib_question")).where(field("del_flag").eq(1)).fetchOneInto(Integer.class);
        Integer ableQuestionNum = dsl.selectCount().from(LIBQUESTIONTB).where(DSL.or(LIBQUESTIONTB.LAST_USE_DATE.isNull(),LIBQUESTIONTB.LAST_USE_DATE.cast(LocalDate.class)
                .le(LocalDate.now().minusYears(3)))).fetchOneInto(Integer.class);
        Integer paperNum = dsl.selectCount().from(table("paper")).fetchOneInto(Integer.class);
        Integer yearPaperNum = dsl.selectCount().from(PAPERTB).where(PAPERTB.CREATE_TIME.cast(LocalDate.class).between(firstDayOfYear,lastDayOfYear)).fetchOneInto(Integer.class);
        Integer okPaperNum = dsl.selectCount().from(PAPERTB).where(PAPERTB.STATE.eq(2)).fetchOneInto(Integer.class);
        res.put("majorNum",majorNum);
        res.put("libNum",libNum);
        res.put("questionNum",questionNum);
        res.put("paperNum",paperNum);
        res.put("okPaperNum",okPaperNum);
        res.put("ableQuestionNum",ableQuestionNum);//可组卷试题数
        res.put("yearPaperNum",yearPaperNum);//今年组卷次数
        return res;
    }
}
